import {Utils, WebStorage} from "jboot-env";
import {Toast} from 'vant';
import Encrypt from "./encrypt";
const keyMapping = {};

export default function (httpConfig, options) {
    httpConfig.api(require.context('./api/', true, /\.js/))
        .baseUrl('/__api/')
        .timeout(1000 * 30)
        .loading(config => {
            const loadingInstance = Toast.loading({
                message: '正在处理...',
                forbidClick: true
            });

            return function close() {
                loadingInstance && loadingInstance.clear();
            }
        })
        .appendPage2Url()
        .headers({
            'gxb-token': function () {
                return WebStorage.localMode().get('{PROJECT_NAME}-token');
            }
        })
	    .before(function (config) {
		    if(config.encrypt && ['request', 'response'].includes(config.encrypt)){
			    let data = config.data, random;

			    // 生产随机密码
			    random = Encrypt.getRandom(8);

			    let encryptKey = Encrypt.rsaEncrypt('公共秘钥', random);

			    // 密码RSA加密
			    config.headers['a-k-l-t'] = encryptKey;

			    keyMapping[encryptKey] = random;

			    if(data) config.data = Encrypt.tripleDESEncrypt(random, JSON.stringify(data));
		    }
	    })
	    .after(function (response) {
		    if(response.config.encrypt && response.config.encrypt === 'response'){
			    let encryptKey = response.config.headers['a-k-l-t'],
				    key = keyMapping[encryptKey];

			    delete keyMapping[encryptKey];

			    let responseData = response.data;

			    if (key && responseData.success === true) {
				    if (responseData.data) {
					    let decryptResponse = Encrypt.tripleDESDecrypt(key, responseData.data);

					    try {
						    decryptResponse = JSON.parse(decryptResponse);
					    } catch (e) {
					    }

					    responseData = Object.assign({}, responseData, {
						    data: decryptResponse
					    })
				    } else {
					    responseData = Encrypt.tripleDESDecrypt(key, responseData);
				    }

				    response.data = responseData;
			    }
		    }
	    })
        .error(error => new Promise((resolve, reject) => {
            let {vue} = options.getInstance(),
                responseInfo = Utils.blank2Default(error.response, {}),
                responseData = Utils.blank2Default(responseInfo.data, {});

	        if (responseData.code === 401) {
                const {pathname, search} = window.location;

                vue.$jump({
                    name: 'login',
                    query: {redirect: [pathname, search].join('')}
                }, true);
	        } else if (responseData.code === 901) {
		        vue.$jump({name: 'permissionFail', query: {message: encodeURIComponent(responseData.message)}}, true);
	        } else {
	            const {message, msg, ...res} = responseData;

                (error.response || {}).data = {...res, message: message || msg};

                reject(error);
            }
        }))
}
